<template>
  <CDialog
    class="dialog"
    :title="`${title}组织信息`"
    v-model:visible="dialogVisible"
    :loading="loading"
    @cancel="handleCancel"
    @confirm="handleClick"
    :before-close="handleCancel"
  >
    <el-form ref="formRef" :model="form" :rules="formRules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="组织类别：" prop="organizationCategory">
            <el-radio-group v-model="form.organizationCategory" placeholder="请选择">
              <el-radio v-for="item in OrgTypeEnumOptions" :key="item.value" :label="item.value">
                {{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="组织标签：" prop="organizationCategory">
            <span v-if="form.tag == 'ENTERPRISE'">{{ OrgTagMap.ENTERPRISE }}</span>

            <el-radio-group v-else v-model="form.tag" placeholder="请选择">
              <el-radio v-for="item in OrgTagEnumOptions" :key="item.value" :label="item.value">
                {{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织名称：" prop="organizationName">
            <el-input v-model="form.organizationName" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业名称：" prop="companyName">
            <el-input v-model="form.companyName" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <template v-if="form.organizationCategory == OrgTypeEnum.ENTITY">
          <el-col :span="24">
            <el-form-item label="公司经营地址：" class="address-select" required> </el-form-item>
            <div class="flex-content">
              <el-form-item prop="province" class="province">
                <CSelect v-model="form.province" placeholder="请选择省" @change="provinceChange">
                  <el-option
                    v-for="item in provinceOptions"
                    :key="item.province"
                    :label="item.provinceName"
                    :value="item.province"
                  />
                </CSelect>
              </el-form-item>
              <el-form-item prop="city" class="city">
                <CSelect v-model="form.city" placeholder="请选择市">
                  <el-option
                    v-for="item in cityOptions"
                    :key="item.city"
                    :label="item.cityName"
                    :value="item.city"
                  />
                </CSelect>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="companyAddress">
              <el-input v-model="form.companyAddress" placeholder="请输入详细地址" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人：" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话：" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系邮箱：" prop="contactEmail">
              <el-input v-model="form.contactEmail" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码：">
              <el-input v-model="form.uscc" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业类型：">
              <CSelect
                style="width: 480px"
                v-model="form.companyType"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in CompanyTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </CSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法定代表人：">
              <el-input v-model="form.legalPerson" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成立日期：">
              <el-date-picker
                style="width: 480px"
                v-model="form.establishmentDate"
                :disabled-date="establishmentDisabledDate"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册资本（万元）：">
              <el-input
                v-model="form.registeredCapital"
                type="number"
                @wheel.stop.prevent
                v-positiveOnly:2
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="注册地址：">
              <el-input v-model="form.registeredAddress" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业：">
              <CSelect style="width: 480px" v-model="form.industry" placeholder="请选择" clearable>
                <el-option
                  v-for="item in IndustryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </CSelect>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="经营范围：">
              <el-input v-model="form.businessScope" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
  </CDialog>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, computed, ref, reactive, inject, onMounted } from 'vue';
import { CDialog } from '@/components/CDialog';
import { emailValidator, mobileValidator } from '@/utils/form-validator';
import { CompanyTypeOptions, IndustryOptions } from '@/constants/enum';
import type { provinceType, cityType } from '@/apis/common/model/commonModel';
import { getCounty } from '@/apis/common/common';
import {
  getOrganizationDetail,
  editOrganization,
  addOrganization
} from '@/apis/system/organization';
import {
  EditOrganizationParams,
  AddOrganizationParams
} from '@/apis/system/model/organizationModel';
import { useMessage } from '@/hooks/useMessage';
import formMitt from '@/hooks/mybus';
import { CSelect } from '@/components/CSelect';
import {
  OrgTypeEnumOptions,
  OrgTypeEnum,
  OrgTagEnumOptions,
  OrgTagMap
} from '@/constants/system/index';
const props = defineProps(['formData', 'visible']);
const { createMessage, createConfirm } = useMessage();
const { refreshTree } = inject('Data');
const emits = defineEmits(['update:visible', 'confirm']);
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});

const init = () => {
  formRef.value?.resetFields();
  if (props.formData?.organizationCode) {
    geDetail(props.formData.id);
    isNew.value = false;
  } else {
    isNew.value = true;
    form.value = {
      organizationCategory: '',
      organizationName: '',
      companyName: '',
      province: '',
      city: '',
      companyAddress: '',
      contact: '',
      contactPhone: '',
      contactEmail: '',
      uscc: '',
      tag: '',
      companyType: '',
      legalPerson: '',
      establishmentDate: '',
      registeredCapital: '',
      registeredAddress: '',
      industry: '',
      businessScope: ''
    };
  }
};
const title = computed(() => {
  return isNew.value ? '新增' : '编辑';
});
onMounted(() => {
  init();
});

const provinceOptions = ref<provinceType[]>([]);
const cityOptions = ref<cityType[]>([]);
const getCountyArr = () => {
  return new Promise(resolve => {
    getCounty('', false).then(res => {
      console.log('getCountyArr_res', res);
      provinceOptions.value = res;
      resolve(res);
      // options.value = handleProvinceTreeData(res);
    });
  });
};
getCountyArr();
const provinceChange = (province: string) => {
  form.value.city = '';
  const index = provinceOptions.value.findIndex(item => item.province == province);
  if (index > -1) {
    cityOptions.value = provinceOptions.value[index].cities;
  }
  // provinceOptions.value.forEach((item: provinceType) => {
  //   if (item.province == province) {
  //     cityOptions.value = item.cities;
  //   }
  // });
};

const establishmentDisabledDate = (time: any) => {
  return time.getTime() > Date.now();
};

const formRef = ref();
const isNew = ref(true);
const form = ref<any>({
  organizationName: '',
  companyName: '',
  province: '',
  city: '',
  companyAddress: '',
  contact: '',
  contactPhone: '',
  contactEmail: '',
  uscc: '',
  companyType: '',
  legalPerson: '',
  establishmentDate: '',
  registeredCapital: '',
  registeredAddress: '',
  industry: '',
  businessScope: ''
});
const formRules = reactive({
  organizationCategory: [
    {
      required: true,
      message: '组织类别不能为空',
      trigger: ['submit', 'change', 'blur']
    }
  ],
  organizationName: [
    {
      required: true,
      message: '组织名称不能为空',
      trigger: ['submit', 'change', 'blur']
    }
  ],
  companyName: [
    {
      required: true,
      message: '企业名称不能为空',
      trigger: ['submit', 'change', 'blur']
    }
  ],
  province: [
    {
      required: true,
      message: '',
      trigger: ['submit', 'change', 'blur']
    }
  ],
  city: [
    {
      required: true,
      message: '',
      trigger: ['submit', 'change', 'blur']
    }
  ],
  companyAddress: [
    {
      required: true,
      message: '详细地址不能为空',
      trigger: ['submit', 'change', 'blur']
    }
  ],
  contact: [
    {
      required: true,
      message: '联系人不能为空',
      trigger: ['submit', 'change', 'blur']
    }
  ],
  contactPhone: [
    {
      required: true,
      message: '联系电话不能为空',
      trigger: ['submit', 'change', 'blur']
    },
    mobileValidator()
  ],
  contactEmail: [
    {
      required: true,
      message: '联系邮箱不能为空',
      trigger: ['submit', 'change', 'blur']
    },
    emailValidator()
  ]
});

const geDetail = (id: number) => {
  getOrganizationDetail(id).then(res => {
    if (!cityOptions.value.length) {
      getCountyArr().then(() => {
        provinceChange(res.province);
        form.value = res;
        form.value.tag = res.tag || '';
      });
    } else {
      form.value = res;
      form.value.tag = res.tag || '';
    }
    console.log(form.value);
    // if (res.userList) {
    //   userList.value = res.userList;
    // } else {
    //   userList.value = [];
    // }
  });
};
const handleClick = () => {
  isNew.value ? addClick() : updateClick();
};
const handleCancel = () => {
  if (isNew.value) {
    // createConfirm('确定取消创建组织？', '取消后将不保存已填写信息', {
    //   iconType: 'warning',
    //   confirmButtonText: '确定'
    // })
    //   .then(() => {
    formMitt.emit('cancelAddAlert');
    dialogVisible.value = false;
    // })
    // .catch(() => {
    //   // dialogVisible.value = false
    //   formMitt.emit('cancelCatch');
    // });
  } else {
    dialogVisible.value = false;
  }
};
//点击更新列表操作
const loading = ref(false);
const updateClick = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      const params: EditOrganizationParams = {
        id: form.value.id,
        organizationName: form.value.organizationName,
        companyName: form.value.companyName,
        companyAddress: form.value.companyAddress,
        province: form.value.province,
        city: form.value.city,
        contact: form.value.contact,
        contactPhone: form.value.contactPhone,
        contactEmail: form.value.contactEmail,
        uscc: form.value.uscc || undefined,
        companyType: form.value.companyType || undefined,
        legalPerson: form.value.legalPerson || undefined,
        establishmentDate: form.value.establishmentDate || undefined,
        registeredCapital: form.value.registeredCapital || undefined,
        registeredAddress: form.value.registeredAddress || undefined,
        industry: form.value.industry || undefined,
        businessScope: form.value.businessScope || undefined,
        organizationCategory: form.value.organizationCategory,
        tag: form.value.tag
      };
      editOrganization(params)
        .then(() => {
          createMessage.success('更新成功');
          loading.value = false;
          //emit('refreshTree', form.value.id);
          dialogVisible.value = false;
          refreshTree(form.value.id);
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};
//点击添加操作
const addClick = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      const params: AddOrganizationParams = {
        parentId: String(props.formData.parentId) as string,
        organizationName: form.value.organizationName,
        companyName: form.value.companyName,
        companyAddress: form.value.companyAddress,
        province: form.value.province,
        city: form.value.city,
        contact: form.value.contact,
        contactPhone: form.value.contactPhone,
        contactEmail: form.value.contactEmail,
        uscc: form.value.uscc || undefined,
        companyType: form.value.companyType || undefined,
        legalPerson: form.value.legalPerson || undefined,
        establishmentDate: form.value.establishmentDate || undefined,
        registeredCapital: form.value.registeredCapital || undefined,
        registeredAddress: form.value.registeredAddress || undefined,
        industry: form.value.industry || undefined,
        businessScope: form.value.businessScope || undefined,
        organizationCategory: form.value.organizationCategory,
        tag: form.value.tag
      };
      addOrganization(params)
        .then((id: number) => {
          createMessage.success('添加成功');
          loading.value = false;
          dialogVisible.value = false;
          //   emit('refreshTree', id);
          refreshTree(id);
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};
</script>

<style lang="scss" scoped>
:deep(.dialog) {
  width: 460px !important;
}
.address-select {
  margin-bottom: 4px;
}
.flex-content {
  display: flex;
  margin-bottom: 8px;
  .province {
    flex: 1;
    margin-right: 8px;
    margin-bottom: 0;
  }
  .city {
    flex: 1;
    margin-bottom: 0;
  }
}
</style>
